<template>
  <div class="gk-layout-container">
    <div class="gk-layout-header">
      <!--工具栏-->
      <div class="toolbar" style="float:left;">
        <el-form :inline="true" :model="filters" :size="global.gSize">
          <el-form-item>
            <el-input v-model="filters.name" :placeholder="$t('item.please enter')"></el-input>
          </el-form-item>



          <el-form-item>
            <kt-button icon="fa fa-search" :label="$t('action.search')" perms="material:item:view" type="primary"
              @click="findPage(null)" />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-plus" :label="$t('action.add')" perms="material:item:add" type="primary"
              @click="handleAdd" />
          </el-form-item>
        </el-form>
      </div>


      <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
        <el-form :inline="true" :size="global.gSize">
          <el-form-item>
            <el-button-group>
              <el-tooltip content="下载模板" placement="top">
                <el-button icon="fa fa-download" @click="exportExample"></el-button>
              </el-tooltip>

              <el-tooltip content="导出Excel" placement="top">
                <el-button icon="fa fa-file-excel-o" @click="exportExcel" />
              </el-tooltip>
              <el-tooltip content="导入Excel" placement="top">
                <el-button icon="fa fa-upload" @click="importExcel" />
              </el-tooltip>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>

    </div>


    <div class="gk-layout-main">
      <my-table :data="pageResult.content" :loading="loading"  >
        <el-table-column :label="$t('action.desc')" width="50" header-align="center" align="center">
          <template slot-scope="scope"> {{scope.$index+1}} </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" width="300" prop="name" label="名称" key="name"/>
        
       
        <el-table-column header-align="center" align="center" prop="fenlei" key="fenlei" label="类别"  :formatter="selectionFormats"/>
        <el-table-column header-align="center" align="center" prop="orderNo" key="orderNo" label="排序"/>
        <el-table-column header-align="center" align="center" prop="active" key="active" label="状态" :formatter="activeStatusFormat"/>
        <el-table-column header-align="center" align="center" :label="$t('action.operation')" width="400">
          <template slot-scope="scope">
            <kt-button icon="fa fa-edit" :label="$t('item.restore')" v-if="scope.row.active=='0'"
              perms="material:item:restore"  @click="handleRestore(scope.$index, scope.row)" />

            <kt-delete-button   v-if="scope.row.active=='1'" perms="material:item:Disable"    @click="handleDisable(scope.$index, scope.row)" />
              
            <kt-button icon="fa fa-edit" :label="$t('action.edit')" perms="material:item:edit"  
              @click="handleEdit(scope.$index, scope.row)" />
        
            <kt-button icon="fa fa-edit" label="同步"    v-if="scope.row.classifyId!=0" perms="material:item:edit"  
              @click="handleInitArea(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </my-table>
    </div>
    <!--分页栏-->
    <div class="toolbar gk-layout-footer" style="padding:10px;">
      <el-pagination layout="total, prev, pager, next, jumper" @current-change="findPage"
        :current-page="pageRequest.pageNum" :page-size="pageRequest.pageSize" :total="pageResult.totalSize"
        style="float:right;">
      </el-pagination>
    </div>








    <!-- EXCEL导入 -->
    <upload-file :key="componentKey" :UpLoadFileVisible="UpLoadFileVisible" @ImportExcelData="ImportExcelData"
      @cancel="cancel" :PercentageValue="this.percentageValue"></upload-file>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'物料 —— 新增':'物料 —— 编辑'" width="40%" :visible.sync="dialogVisible"
      :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="90px" :rules="dataFormRules" ref="dataForm" :size="global.gSize"
        label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>
      
        <el-form-item label="编码" prop="code">
          <el-input v-model="dataForm.code" auto-complete="off"></el-input>
        </el-form-item>
       
        <el-form-item label="分类" prop="fenlei">
          <el-select v-model="dataForm.fenlei" placeholder="请选择" style="width: 100%;" >
            <el-option v-for="item in dicts.fenlei" :key="item.value"   :label="item.label"  :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        


       
        </el-form-item>
        <el-form-item label="排序" prop="orderNo">
          <el-input v-model="dataForm.orderNo" auto-complete="off" placeholder=""
            onkeyup="value=value.replace(/[^0-9]/g,'')" clearable></el-input>
        </el-form-item>
      
        <el-form-item :label="$t('item.classifyId')" prop="classifyId">
          <el-select v-model="dataForm.classifyId" placeholder="请选择" style="width: 100%;" clearable filterable>
            <el-option v-for="item in classTypes" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="global.gSize" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="global.gSize" type="primary" @click.native="submitForm">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import PopupTreeInput from "@/components/PopupTreeInput"
  import KtDeleteButton from "@/views/Core/KtDeleteButton"
  import KtButton from "@/views/Core/KtButton"
 
  import { format } from "@/utils/datetime"
  import UploadFile from "@/views/Core/UploadFile"
  import { myXlsExport } from "@/excel/myXls"
  import XLSX from "xlsx";
  import MyTable from "@/views/Core/MyTable"
  export default {
    components: {
      PopupTreeInput,
MyTable,
      KtButton,KtDeleteButton,
 
      UploadFile
    },

    data() {

      return {
  
        loading: false,
        filters: {
          name: ''
        },
        percentageValue: 0,
        columns: [],
        filterColumns: [],
        pageRequest: { pageNum: 1, pageSize: 20 },
        pageResult: {},
        tableData: [],
        componentKey: 0,
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        UpLoadFileVisible: false,
        editLoading: false,
        dicts: this.$store.state.dict.dicts,
        // 新增编辑界面数据
        dataForm: {
          id: 0,

          orderNo:1
        },
        classTypes: [],
      }
    },

    computed: {
      dataFormRules() {
        const dataFormRules = {
          name: [{ required: true, message: "请输入名称", trigger: 'blur' }],
          
        };
        return dataFormRules;
      }
    },

    methods: {
      //获取分页数据
      findPage: function (data) {

        if (data !== null) {
          this.filters.pageNum = data
        } else {
          this.filters.pageNum = 1
        }
        this.filters.pageSize = this.pageRequest.pageSize
        this.loading = true;
        this.$api.item.findPage(this.filters).then((res) => {
          this.pageResult = res.data
          this.loading = false;
        }).then(data != null ? data.callback : '')
      },
      // 加载用户角色信息
      findUserRoles: function () {
        this.$api.role.findAll().then((res) => {
          // 加载角色集合
          this.roles = res.data
        })
      },
      importExcel() {
        this.componentKey += 1;
        this.UpLoadFileVisible = true
      },
      ImportExcelData(excelData) {
        // 将上面数据转换成 table需要的数据
        let arr = [];
        excelData.forEach(item => {
          let obj = {};
          obj.name = item["名称"];
          obj.classifyId = this.classTypeToId(item["类别名称"]);
          obj.coreItemType = this.dicToId(item["物料类型"]);
          obj.code = item["编码"];
          obj.modelSpecs = item["规格型号"];
          obj.packageSpecs = item["包装规格"];
          arr.push(obj);
          this.percentageValue = Math.round(this.percentageValue + 100 / excelData.length)
          // this.$api.item.save(obj).then((res) => {
          //     if(res.code==200){
         
          //         this.percentageValue= this.percentageValue+100/excelData.length
          //     }
          //     else
          //     {
          //         this.percentageValue=0
          //     }
          // })
        });
        this.$api.item.ImportList(arr).then((res) => {
          if (res.code == 200) {
            this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
            this.UpLoadFileVisible = false
            this.findPage(null)
            this.percentageValue = 0
          }
          else {
            this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
            this.UpLoadFileVisible = false
            this.percentageValue = 0
          }

        })


      },
      cancel: function () {
        this.UpLoadFileVisible = false;
        this.percentageValue = 0
      },
      //导出的方法
      exportExcel() {
      
 
        this.$api.item.GetExportList(this.filters).then((res) => {
          const tHeader = ['名称', '类别名称', '物料类型', '编码', '规格型号', '包装规格'];
          const filterVal = ['name', 'classifyName', 'coreItemTypeName', 'code', 'modelSpecs', 'packageSpecs'];
          myXlsExport(tHeader, filterVal ,res.data, '物料信息导出');
        })
      
      },
      
      //下载模板
      exportExample() {
            const tHeader = ['名称', '类别名称', '物料类型', '编码', '规格型号', '包装规格'];
            const filterVal = ['name', 'classifyName', 'coreItemTypeName', 'code', 'modelSpecs', 'packageSpecs'];
            myXlsExport(tHeader, filterVal ,[], '物料信息模板');

      },
      // 批量删除
      handleDelete: function (data) {
        this.$api.item.batchDelete(data.params).then(data != null ? data.callback : '')
      },
      // 显示新增界面
      handleAdd: function () {

        this.dialogVisible = true
        this.operation = true
        this.dataForm = {

        }
      },
      selectionFormats: function (row, column, cellValue, index) {
        let key  = column.property;
       
        let val = row[column.property];
        let dict = this.dicts[key];
        if (dict == undefined) {
          return row[column.property]
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == val) {
            return dict[i].label;
          }
        }
        return row[column.property]
      },

      // 显示编辑界面
      handleEdit: function (index, row) {

        this.dialogVisible = true
        this.operation = false
        this.dataForm = Object.assign({}, row)
      },
      //取消
      cancelForm: function () {
        if (this.$refs['dataForm'] != undefined) {
          this.$refs['dataForm'].resetFields();
        }

        this.dialogVisible = false
      },
      //新增
      submitForm: function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
              this.editLoading = true
              let params = Object.assign({}, this.dataForm)
              this.$api.item.save(params).then((res) => {
                //this.editLoading = false
                if (res.code == 200) {
                  this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
                  this.dialogVisible = false
                  this.$refs['dataForm'].resetFields()
                } else {
                  this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
                }
                this.findPage(null)
              })
            })
          }
        })
      },
      //`恢复
      handleRestore: function (index, row) {
        this.dataForm = Object.assign({}, row)
        if (this.dataForm.active == "正常") {
          this.$confirm('你选中的物料已经是正常状态了', '提示', {
            type: 'warning'
          })
        } else {
          this.dataForm.active = 1;
          this.$api.item.restore(this.dataForm).then((res) => {
            if (res.code == 200) {
              this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
              this.dialogVisible = false
            } else {
              this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
            }
            this.findPage(null)
          })
        }
      },

      handleInitArea: function (index, row) {
        this.dataForm = Object.assign({}, row)
      
          this.dataForm.active = 1;
          this.$api.item.initArea(this.dataForm).then((res) => {
            if (res.code == 200) {
              this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
              this.dialogVisible = false
            } else {
              this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
            }
            this.findPage(this.filters.pageNum)
          })
        
      },
      handleDisable: function (index, row) {
        this.dataForm = Object.assign({}, row)
        if (this.dataForm.active == "禁用") {
          this.$confirm('你选中的物料已经是禁用状态了', '提示', {
            type: 'warning'
          })
        } else {
          this.dataForm.active = 0;
          this.$api.item.disable(this.dataForm).then((res) => {
            if (res.code == 200) {
              this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
              this.dialogVisible = false
            } else {
              this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
            }
            this.findPage(null)
          })
        }
      },
      // 菜单树选中
      deptTreeCurrentChangeHandle(data, node) {
        this.dataForm.deptId = data.id
        this.dataForm.deptName = data.name
      },
      // 时间格式化
      dateFormat: function (row, column, cellValue, index) {
        return format(row[column.property])
      },
      //加载物料类别分类
      findClassTypes: function () {
        this.$api.classify.findPage().then((res) => {
          this.classTypes = res.data.content
        })
      },
      
      // 处理表格列过滤显示
      handleFilterColumns: function (data) {
        this.filterColumns = data.filterColumns
        this.$refs.tableColumnFilterDialog.setDialogVisible(false)
      },
      getKey: function (arg) {
        return this.$t(arg)
      },


      selectionFormat: function (row, column, cellValue, index) {
        let key = ""
        let propt = column.property;
        let val = row[column.property];
        let dict = this.classTypes;
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].id == val) {
            return dict[i].name;
          }
        }
        return val
      },
      classifyidtype: function (row, column, cellValue, index) {
        let val = parseInt(row["classifyId"]);
        let dict = this.classTypes;
        if (dict == undefined) {
          return row[column.property]
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].id == val) {
            return dict[i].name;
          }
        }
        return row[column.property]
      },
      activeStatusFormat: function (row, column, cellValue, index) {
   

        let dict = this.dicts["itemActive"];
        if (dict == undefined) {
          return cellValue
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == cellValue) {
            return dict[i].label;
          }
        }
        return cellValue

      },
      classTypeToId: function (name) {
        let list = this.classTypes;
        for (let i = 0; i < list.length; i++) {
          if (list[i].name == name) {
            return list[i].id;
          }
        }
        return 0
      },

      idToClassType: function (id) {
        let list = this.classTypes;
        for (let i = 0; i < list.length; i++) {
          if (list[i].id == id) {
            return list[i].name;
          }
        }
        return id
      },

      dicToId: function (name) {
        let dict = this.dicts["coreItemType"];
        if (dict == undefined) {
          return 0
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].label == name) {
            return dict[i].value;
          }
        }
        return 0
      },

      idToDic: function (id) {
        let dict = this.dicts["coreItemType"];
        if (dict == undefined) {
          return id
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == id) {
            return dict[i].label;
          }
        }
        return id
      },
      selectionFormat1: function (row, column, val, index) {

        //let val=row["isSorting"];
        let dict = this.dicts["itemSorting"];
        if (dict == undefined) {
          return val
        }
        for (let i = 0; i < dict.length; i++) {
          if (dict[i].value == val) {
            return dict[i].label;
          }
        }
        return val
      },
    },


    created() {
      //this.findDeptTree()

      this.findClassTypes()

      this.dicts = this.$store.state.dict.dicts;
      this.findPage(null);
    },
    watch: {
      $UpLoadFileVisible(to, from) {
        console.log(to);
        console.log(from);
      },
      dialogVisible(to, from) {
        if (this.$refs['dataForm'] !== undefined) {
          this.$refs["dataForm"].resetFields();
        }
      }
    }
  }

</script>

<style scoped>
</style>